using Digitalmes.Domain.Entities.Mes.Qualities;

namespace Digitalmes.Application.Mes.Qulities.Defects.Commands;

/// <summary>
/// 缺陷定义创建命令。
/// </summary>
public sealed record CreateDefectCommand(QcDefectDefineDto Defect) : IRequest<IResult<bool>>;

internal sealed class CreateDefectCommandHandler(IRepository<QcDefectDefine> repo) : IRequestHandler<CreateDefectCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateDefectCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.DefectCode == request.Defect.DefectCode, cancellationToken))
        {
            return Result.Failure("缺陷代码已存在");
        }

        var defect = request.Defect.Adapt<QcDefectDefine>();
        var ok = await repo.InsertAsync(defect, cancellationToken);
        return Result.From(ok);
    }
}
